package cz.muni.fi.pa165.travelagency.services;

import cz.muni.fi.pa165.travelagency.api.entities.ITour;
import cz.muni.fi.pa165.travelagency.api.services.IPackageTourService;
import cz.muni.fi.pa165.travelagency.api.services.ITourService;
import cz.muni.fi.pa165.travelagency.dto.TourDTO;
import cz.muni.fi.pa165.travelagency.entities.Tour;
import cz.muni.fi.pa165.travelagency.interceptors.ShiroSecured;
import cz.muni.fi.pa165.travelagency.persistence.ITourDAO;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dozer.DozerBeanMapperSingletonWrapper;
import org.dozer.Mapper;

/**
 * Tour service implementation
 *
 * @author Petr Stribny
 * @created 02-11-2012
 * @version 1.0
 */
@Stateless(name = "tourService", mappedName = "tourService")
@Local(ITourService.class)
@TransactionManagement(value=TransactionManagementType.CONTAINER)
@ShiroSecured
public class TourService implements ITourService {

    private Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
    
    @EJB
    private ITourDAO tourDAO;
    
    void setTourDao(ITourDAO tourDAO)
    {
        this.tourDAO = tourDAO;
    }

    public void setMapper(Mapper mapper) {
        this.mapper = mapper;
    }
    
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @RequiresPermissions("tour:create")
    public void createTour(ITour tour) {
        Tour t = mapper.map(tour, Tour.class);
        tourDAO.createTour(t);
        tour.setId(t.getId());
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @RequiresPermissions("tour:delete")
    public void deleteTour(ITour tour) {
        tourDAO.deleteTour(mapper.map(tour, Tour.class));
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @RequiresPermissions("tour:find")
    public int getAvailablePlaces(ITour tour) {
        return tourDAO.getAvailablePlaces(mapper.map(tour, Tour.class));
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @RequiresPermissions("tour:find")
    public ITour getTour(Long id) {
        Tour t = tourDAO.getTour(id);
        return t == null ? null : mapper.map(t, TourDTO.class);
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @RequiresPermissions("tour:update")
    public void updateTour(ITour tour) {
        tourDAO.updateTour(mapper.map(tour, Tour.class));
    }
}
